/*
 * Powered By xTOOLs
 * Dev by DuRisk@pactera.com
 * Copyright © 2009 - 2017 pactera.com. All rights reserved.
 *
 * Generated at 2017年12月25日 10:52:48
 *
 */

package com.pactera.jep.service.sys.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.core.context.Context;
import com.pactera.jep.core.entity.Identity;
import com.pactera.jep.service.sys.model.UserProfile;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.sys.code.MetaQueryStatus;
import com.pactera.jep.sys.code.MetaQueryType;
import com.pactera.jep.sys.model.MetaQuery;
import com.pactera.jep.sys.model.MetaRegionTable;
import com.pactera.jep.sys.model.MetaTable;
import com.pactera.jep.sys.query.constant.QueryOptions;
import com.pactera.jep.sys.query.constant.QueryRelationType;
import com.pactera.jep.sys.query.dto.QueryDto;
import com.pactera.jep.sys.query.dto.QueryResultDto;
import com.pactera.jep.sys.service.MetaQueryService;
import com.pactera.jep.sys.service.MetaRegionTableService;
import com.pactera.jep.sys.service.MetaRelationService;
import com.pactera.jep.sys.service.MetaTableService;
import com.pactera.jep.sys.util.JSONDateValueProcessor;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.controller.CrudController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.pactera.jep.autoconfigure.web.controller.BaseRestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Api(value = "元数据查询")
@RestController
@RequestMapping("/metaQuery")
public class MetaQueryRestController extends BaseRestController<MetaQuery>{
	private static Logger	logger	= LoggerFactory.getLogger(MetaQueryRestController.class);

	@Autowired
	private MetaQueryService		metaQueryService;
	
	@Autowired
	private MetaRegionTableService	metaRegionTableService;
	
	@Autowired
	private MetaRelationService		metaRelationService;
	
	@Autowired
	private MetaTableService		metaTableService;
	
	
	
	/**
	 * 获取列表页面
	 * @return 列表页面
	 */
	@RequestMapping(value = "/list")
	public String list(Model model) {
		
		return "sys/metaQueryList";
	}
	
	/**
	 * 为列表页面做数据准备
	 */
	@Override
	protected void prepareQuery(String token, Page<MetaQuery> page, List<Filter> filters, List<Order> orders, HttpServletRequest request) {
		
		metaQueryService.query(page, filters, orders);
	}
	
	/**
	 * 新增页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/add")
	public String add(Model model){
		
		return "sys/metaQueryEdit";
	}
	
	
	/**
	 * 查看页面
	 * @param queryId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/view/{queryId}")
	public String view(@PathVariable String queryId, Model model) {
		
		MetaQuery metaQuery = metaQueryService.get(queryId);
		metaQuery.setQueryType(MetaQueryType.getLabel(metaQuery.getQueryType()));
		metaQuery.setStatus(MetaQueryStatus.getLabel(metaQuery.getStatus()));
		model.addAttribute("metaQuery", metaQuery);
		
		return "sys/metaQueryView";
	}
	
	/**
	 * 保存
	 * @param metaQuery
	 * @return
	 */
	@ApiOperation(value = "保存")
	@PostMapping(value = "/save")
	@ResponseBody
	public Map<String, Object> save(@RequestBody MetaQuery metaQuery) {
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		Boolean isExist = metaQueryService.exists(metaQuery.getQueryId());
		try 
		{
			if(isExist)
			{
				
				metaQueryService.updateSelective(metaQuery);
			}
			else
			{
				/*UserProfile profile = UserProfileUtils.getUserProfile();*/
				/*String staffCode = Context.getIdentityContext().getIdentity().getId();*/
				Identity identity = Context.getIdentityContext().getIdentity();

				if(identity == null)
				{
					throw new ServiceException("user session may be expired.");
				}
				
				 /*验证同已用户在同一张表下名字不能重复*/
				List<Filter> filters = new Filter.Builder().eq("staffCode", identity.getId())
						.eq("tableId", metaQuery.getTableId()).eq("queryName", metaQuery.getQueryName()).build();
				boolean existsQueryName = metaQueryService.exists(filters );
				if(existsQueryName){
					tips.put(WebCode.SUCCESS, false);
					tips.put(WebCode.MSG, "查询名称重复，请重新录入！");
					return tips;
				}
				
				metaQuery.setUnitCode(identity.getUnitCode());
				metaQuery.setUnitName(identity.getUnitName());
				metaQuery.setDeptCode(identity.getDeptCode());
				metaQuery.setDeptName(identity.getDeptName());
				metaQuery.setStaffCode(identity.getId());
				metaQuery.setStaffName(identity.getName());
				metaQuery.setStatus(MetaQueryStatus.FORCE.getValue());
				
				metaQueryService.insert(metaQuery);
			}
			
			tips.put(WebCode.SUCCESS, true);
			tips.put("queryId", metaQuery.getQueryId());
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		}
		catch (ServiceException e) 
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}
		return tips;
	}
	/**
	 * 删除
	 * @param queryId
	 * @return
	 */
	@ApiOperation("删除对应的查询")
	@PostMapping(value = "/remove/{queryId}")
	public Map<String, Object> remove(@PathVariable String queryId){
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		try 
		{
			metaQueryService.deleteByPrimaryKey(queryId);
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
		} 
		catch (ServiceException e) 
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
		}
		
		return tips;
	}
	
	/**
	 * 验证提交的queryId是否已经存在数据库中
	 * @param queryId
	 * @return
	 */
	@RequestMapping(value = "/check", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> check(String queryId){
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		boolean exist = metaQueryService.exists(queryId);
		tips.put("valid", !exist);
		
		return tips;
	}
	
	/**
	 * 根据一个tableId初始化metaQuery对象
	 * @param
	 * @return
	 * @throws Exception
	 */

    @ApiOperation(value = "根据一个tableId初始化metaQuery对象")
	@PostMapping(value = "/get")
	public Map<String, Object> getMeatQuery(@RequestBody JSONObject params) throws Exception {

    	String regionTableId = params.getString("regionTableId");
		Map<String, Object> map = new HashMap<String, Object>();
		//UserProfile profile = UserProfileUtils.getUserProfile();
        /*获取用户信息*/
        String staffCode = Context.getIdentityContext().getIdentity().getId();
		/*if(profile == null)
		{
			throw new ServiceException("user session may be expired.");
		}*/
		
		/*获取regionTable对象*/
		MetaRegionTable regionTable = metaRegionTableService.get(regionTableId);
		
		/*初始化一个query对象*/
		QueryDto query = metaQueryService.init(regionTable.getTableId(), regionTableId, staffCode);
		query.setTableId(regionTableId);
		
		/*获得脚步*/
		String script = query.getScript();
		JSONObject jsonScript =  JSONObject.parseObject(script);
		jsonScript.put("limit", 10);
		jsonScript.put("pageNo", 1);
		
		query.setScript(jsonScript.toJSONString());
		
		/*查询结果*/
		QueryResultDto result = metaQueryService.query(query, QueryOptions.BUILD_OPTION_PRIVILEGE_REQUIRED, staffCode);
		
		/*初始化所有关联表数据*/
		map.put("joinTable", metaRelationService.selectJoinTablesByTableId(regionTable.getTableId(), staffCode));
		map.put("masterTable", metaRelationService.selectMasterTablesByTableId(regionTable.getTableId(), staffCode));
		
		map.put(WebCode.SUCCESS, true);
		map.put("metaQuery", query);
		map.put("result", result);
		map.put("resultData", JSONDateValueProcessor.Object2JsonString(result.getResult()));
		
		return map;
	}
	

	/**
	 * 查询一个metaQuery
	 * @throws Exception
	 */
	@ApiOperation(value = "根据一个查询初始化metaQuery对象")
	@PostMapping(value = "/edit")
	public Map<String, Object> queryMeatQuery(@RequestBody JSONObject params) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		String queryId = params.getString("regionTableId");
		//UserProfile profile = UserProfileUtils.getUserProfile();
        String staffCode = Context.getIdentityContext().getIdentity().getId();
		if(staffCode == null)
		{
			throw new ServiceException("user session may be expired.");
		}

		MetaQuery metaQuery = metaQueryService.get(queryId); 
		
		/*初始化queryDto对象*/
		QueryDto query = new QueryDto();
		query.setScript(metaQuery.getScript());
		
		QueryResultDto result = metaQueryService.query(query, QueryOptions.BUILD_OPTION_PRIVILEGE_REQUIRED, staffCode);;
		
		MetaRegionTable metaRegionTable = metaRegionTableService.get(metaQuery.getTableId());
		MetaTable metaTable = metaTableService.get(metaRegionTable.getTableId());
		
		/*初始化所有关联表数据*/
		map.put("joinTable", metaRelationService.selectJoinTablesByTableId(metaTable.getTableId(), staffCode));
		map.put("masterTable", metaRelationService.selectMasterTablesByTableId(metaTable.getTableId(), staffCode));
		
		map.put(WebCode.SUCCESS, true);
		map.put("metaQuery", metaQuery);
		map.put("result", result);
		map.put("resultData", JSONDateValueProcessor.Object2JsonString(result.getResult()));
		
		return map;
	}
	/**
	 * 根据脚本查询数据
	 * @param script
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "根据脚本查询数据")
	@PostMapping(value = "/queryResult")
	@ResponseBody
	public Map<String, Object> queryResult(@RequestBody String script, HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonObject = JSONObject.parseObject(script);
		script = jsonObject.getString("script");
		//UserProfile profile = UserProfileUtils.getUserProfile();
        String staffCode = Context.getIdentityContext().getIdentity().getId();
		if(staffCode == null)
		{
			throw new ServiceException("user session may be expired.");
		}
		/*初始化queryDto对象*/
		QueryDto query = new QueryDto();
		query.setScript(script);
		
		/*查询结果*/
		QueryResultDto result = metaQueryService.query(query, QueryOptions.BUILD_OPTION_PRIVILEGE_REQUIRED, staffCode);;
		map.put(WebCode.SUCCESS, true);
		map.put("result", result);
		map.put("query", query);
		map.put("resultData", JSONDateValueProcessor.Object2JsonString(result.getResult()));
		
		return map;
	}
	
	/**
	 * 增加关联表
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/join")
	public String addJoinTable(Model model) {
		return "sys/metaQueryJoinDlg";
	}
	
	/**
	 * 获取选择表页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tableDlg")
	public String joinTableDlg(String joinAlias, Model model) {
		model.addAttribute("joinAlias", joinAlias);
		return "sys/metaQueryTableDlg";
	}
	
	/**
	 * 选择关联条件
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/joinCons")
	public String joinCondition(Model model) {
		return "sys/metaQueryJoinConsDlg";
	}
	
	/**
	 * 获取选择字段页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/selectColumn")
	public String selectColumn(Model model) {
		return "sys/metaQuerySelectColumnDlg";
	}
	
	/**
	 * 获取自定义字段页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/customColumn")
	public String customColumn(Model model) {
		return "sys/metaQueryCustomColumnDlg";
	}
	
	/**
	 * 获取选择条件页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/condition")
	public String condition(Model model) {
		return "sys/metaQueryConditionDlg";
	}
	
	/**
	 * 获取选择排序字段页面
	 * @return 选择字段页面
	 */
	@RequestMapping(value = "/order")
	public String modelSelectedColumns(Model model) {
		return "sys/metaQueryOrderColumn";
	}
	
	/**
	 * 选择分组汇总字段
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/groupColumns")
	public String groupColumns(Model model) {
		return "sys/metaQueryGroupColumn";
	}
	
	/**
	 * 验证自定义查询是否是自己创建
	 * @param queryId
	 * @return
	 */
	@ApiOperation("验证自定义查询是否是自己创建")
	@PostMapping("/verify")
	public Map<String, Object> verify(@RequestBody String queryId)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		//UserProfile profile = UserProfileUtils.getUserProfile();
        String staffCode = Context.getIdentityContext().getIdentity().getId();
		if(staffCode == null)
		{
			throw new ServiceException("user session may be expired.");
		}
		
		MetaQuery metaQuery = metaQueryService.get(queryId);
		
		if(metaQuery != null){
			if(metaQuery.getStaffCode().equals(staffCode))
			{
				map.put(WebCode.SUCCESS, true);
			}
			else
			{
				map.put(WebCode.SUCCESS, false);
			}
		}
		return map;
	}
/*	@RequestMapping(value = "/saveView")
	@ResponseBody
	public Map<String, Object> saveView(@RequestBody String param) {
		JSONObject jsonObject = JSONObject.parseObject(param);

		return  null;
	}*/
	/**
	 * 另存为视图
	 * @param queryDto
	 * @param metaTable
	 * @return
	 */
    @ApiOperation(value = "另存为视图")
	@PostMapping(value = "/saveView")
	public Map<String, Object> saveView(@RequestBody String param, MetaTable metaTable, QueryDto queryDto,    String regionId) {
		Map<String, Object> tips = new HashMap<String, Object>();
		try {
			//UserProfile profile = UserProfileUtils.getUserProfile();
            String staffCode = Context.getIdentityContext().getIdentity().getId();
			if(staffCode == null)
			{
				throw new ServiceException("user session may be expired.");
			}
			JSONObject jsonObject = JSONObject.parseObject(param);
			metaTable.setSchema(jsonObject.getString("schema"));
			metaTable.setTableCode(jsonObject.getString("tableCode"));
			metaTable.setTableName(jsonObject.getString("tableName"));
			queryDto.setScript(jsonObject.getString("script"));
			regionId = jsonObject.getString("regionId");
			MetaRegionTable metaRegionTable = metaQueryService.saveAsView(queryDto, metaTable, regionId, staffCode);
			tips.put("tableId", metaRegionTable.getRegionTableId());
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}
		return tips;
	}

	/**
	 * 查询子表数据
	 * @param masterTableId
	 * @param
	 * @param data
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryChild", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> queryChild(String masterTableId, String masterColumnCode, String joinTableId, String joinColumnCode, String data, String relationType, HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		data = URLDecoder.decode(data, "UTF-8");
		
		//UserProfile profile = UserProfileUtils.getUserProfile();
        String staffCode = Context.getIdentityContext().getIdentity().getId();
		if(staffCode == null)
		{
			throw new ServiceException("user session may be expired.");
		}
		
		/*关联表表 regionTable对象*/
		MetaRegionTable masterRegionTable = null;
		
		/*当前表 regionTable对象*/
		MetaRegionTable relativeRegionTable = null;
		String regionTableId = "";
		
		/*查询主表*/
		if(QueryRelationType.valueOf(relationType).equals(QueryRelationType.MASTER))
		{
			/*关联表表 regionTable对象*/
			masterRegionTable = metaRegionTableService.get(joinTableId);
			
			/*当前表 regionTable对象*/
			relativeRegionTable = metaRegionTableService.get(masterTableId);
			regionTableId = relativeRegionTable.getRegionTableId();
		}
		else
		{
			/*关联表表 regionTable对象*/
			masterRegionTable = metaRegionTableService.get(masterTableId);
			
			/*当前表 regionTable对象*/
			relativeRegionTable = metaRegionTableService.get(joinTableId);
			regionTableId = masterRegionTable.getRegionTableId();
		} 
		
		/*初始化query对象*/
		QueryDto query = null;
		QueryResultDto result = null;
		
		map.put(WebCode.SUCCESS, true);
		
		try {
			query = metaQueryService.init(masterRegionTable.getTableId(), masterColumnCode, relativeRegionTable.getTableId(), joinColumnCode, regionTableId, QueryRelationType.valueOf(relationType), data);
			query.setTableId(masterTableId);
			
			/*查询结果*/
			result = metaQueryService.query(query, QueryOptions.BUILD_OPTION_PRIVILEGE_REQUIRED, staffCode);
		} catch (Exception e) {
			map.put(WebCode.SUCCESS, false);
			map.put(WebCode.MSG, "查询数据失败。");
		}
		
		/*初始化所有关联表数据*/ 
		map.put("joinTable", metaRelationService.selectJoinTablesByTableId(metaRegionTableService.get(masterTableId).getTableId(), staffCode));
		map.put("masterTable", metaRelationService.selectMasterTablesByTableId(metaRegionTableService.get(masterTableId).getTableId(), staffCode));
		
		map.put("query", query);
		map.put("result", result); 
		map.put("resultData", JSONDateValueProcessor.Object2JsonString(result.getResult()));
		return map;
	}
	
	
	/**
	 * 查看数据
	 * @param queryId
	 * @param model
	 * @return
	 */
	@RequestMapping("/viewMetaDataProvider/{queryId}")
	public String viewMetaDataProvider(@PathVariable String queryId,Model model){
		MetaQuery metaQuery = metaQueryService.get(queryId);
		metaQuery.setQueryType(MetaQueryType.getLabel(metaQuery.getQueryType()));
		metaQuery.setStatus(MetaQueryStatus.getLabel(metaQuery.getStatus()));
		model.addAttribute("metaQuery", metaQuery);
		return "sys/metaDataProviderView";
	}
}